package org.git.movie.videojiexi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.git.movie.videojiexi.common.util.VideoHelper;
import org.git.movie.videojiexi.enums.VideoChannel;
import org.git.movie.videojiexi.model.VideoModel;
import org.git.movie.videojiexi.service.VideoService;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service("TencentQqServiceImpl")
public class TencentQqServiceImpl  implements VideoService {
    private static Logger log = LoggerFactory.getLogger(TencentQqServiceImpl.class);
    /**
     * 如何获取视频地址：
     * 在视频上-->点击鼠标右键-->复制视频页面地址
     * @param url
     * @param userAgent
     * @return
     * @throws Exception
     */
    @Override
    public VideoModel parseUrl(String url, String userAgent) throws Exception {
        int qxd = 1;//视频类型， 1：标清；2：高清
        String    queryString = url.replaceFirst("https://m.v.qq.com/play.html","");

        if(queryString.startsWith("?")){
            queryString = queryString.replaceFirst("\\?","");
        }
        queryString = queryString.trim();

        Map<String,String> queryMap = VideoHelper.parse2Map(queryString);
        String vids = queryMap.get("vid");

        String bqApi = "http://vv.video.qq.com/getinfo?vids={vids}&platform=101001&charge=0&otype=json&defn=hd";
        String gqApi = "http://vv.video.qq.com/getkey?format=2&otype=json&vt=150&vid={vids}&ran={rand}&charge=0&filename={vids}.mp4&platform=11";

        bqApi = bqApi.replace("{vids}",vids);
        gqApi = gqApi.replace("{vids}",vids);
        gqApi = gqApi.replace("{rand}",System.currentTimeMillis()+"");

        Map<String, String> headers = new HashMap<>();
        headers.put("Connection", "keep-alive");
        if(userAgent == null || userAgent.length() ==0){
            userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 Version/12.0 Safari/604.1";
        }
        headers.put("User-Agent", userAgent);

        //6.利用Joup获取视频对象,并作封装成一个输入流对象
        String html = Jsoup.connect(bqApi).headers(headers).timeout(10000).ignoreContentType(true).execute().body();
        html = html.replaceFirst("QZOutputJson=","");
        html = html.trim();
        if(html != null && html.endsWith(";")){
            html = html.substring(0,html.length()-1);
        }
        System.out.println(html);

        JSONObject api1Json = JSON.parseObject(html);
        JSONObject vl = api1Json.getJSONObject("vl");
        JSONArray vi = vl.getJSONArray("vi");
        JSONObject viObj = vi.getJSONObject(0);

        JSONObject ul =viObj.getJSONObject("ul");
        JSONArray ui = ul.getJSONArray("ui");
        JSONObject uiObj = ui.getJSONObject(0);

        String preUrl = uiObj.getString("url");
        String fn = viObj.getString("fn");
        String vkey = viObj.getString("fvkey");
        String ti  = viObj.getString("ti");

      String   downloadUrl = preUrl+ fn + "?vkey=" + vkey;

//
        VideoModel rep = new VideoModel();
//        rep.setCover(picUrl);
//        rep.setFileType(fileType);
        rep.setPlayAddr(downloadUrl);
        rep.setChannel(VideoChannel.TencentQq);
        rep.setName(ti);

        return rep;
    }



    private String getVids(String url){
        String[] arUrl = url.split(".html")[0].split("/");
        return arUrl[arUrl.length-1];
    }

    public static void main(String[] args) throws Exception {
        VideoModel rep =   new TencentQqServiceImpl().parseUrl("https://v.qq.com/x/page/c0847oed6ub.html","");
        log.info(JSON.toJSONString(rep));


//        VideoModel rep2 =   new TencentQqServiceImpl().parseUrl("https://m.v.qq.com/play.html?vid=x3037227u8z","");
//        log.info(JSON.toJSONString(rep2));


    }
}
